package top100;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Godc
 * @description
 */
public class ThreadTest {
    private volatile static boolean flag;
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    static int i = 0,j = 0;
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            try {
                lock.lock();
                while(i<10){
                    if(flag){
                        try {
                            conditionA.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    flag = true;
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                    i++;
                    conditionB.signal();
                }
            }finally {
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            try {
                lock.lock();
                while(j<10){
                    if(!flag){
                        try {
                            conditionB.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    flag = false;
                    System.out.println(Thread.currentThread().getName()+"-->"+j);
                    j++;
                    conditionA.signal();
                }
            }finally {
                lock.unlock();
            }
        }).start();

        Thread.sleep(1000);
    }
}
